package com.cykj.page01;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @BelongsProject: MyTomcat
 * @BelongsPackage: com.cykj.page04
 * @Author: WWJ
 * @CreateTime: 2025-06-25 15:33
 * @Description: TODO
 * @Version: 1.0
 */
public class MyHttpResponse {
    private Socket socket;
    public MyHttpResponse(Socket socket) {
        this.socket = socket;
    }

    public void write(byte[] bytes){this.write("text/html",bytes);}

    public void write(String media, byte[] bytes) {
        try {
            OutputStream os = socket.getOutputStream();

            // 写入 HTTP 响应头
            os.write("HTTP/1.1 200 OK".getBytes());
            os.write("\r\n".getBytes());
            os.write(("Content-Type:" + media + ";charset=UTF-8").getBytes());
            os.write("\r\n".getBytes());
            os.write(("Content-Length:" + bytes.length).getBytes());  // 修正了行末换行符
            os.write("\r\n".getBytes());  // 空行，结束头部部分
            os.write("\r\n".getBytes());

            // 写入响应体（图片字节流）
            os.write(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
